/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.exception.diagnostic.analyzer;

import io.iec.edp.caf.commons.exception.diagnostic.entity.ConstantInfos;
import lombok.var;
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
import org.springframework.boot.diagnostics.FailureAnalysis;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 文件找不到异常，重点处理以下问题：
 * 1. Too many open files
 * 2.
 * @author wangyandong
 * @date 2021/09/01 14:11
 *
 */
public class FileNotFoundFailureAnalyzer extends AbstractFailureAnalyzer<FileNotFoundException> {

    @Override
    protected FailureAnalysis analyze(Throwable rootFailure, FileNotFoundException cause) {
        if(cause.getMessage().toLowerCase().contains("too many open files")) {
            return new FailureAnalysis("句柄数超出系统限制（Too many open files）",
                    "将文件句柄数调整为较大数值，一、临时修改：执行命令 ulimit -n number；二、将ulimit 值添加到/etc/profile文件中（适用于有root权限登录的系统）",
                    rootFailure);
        }else{
            String className = cause.getMessage().toLowerCase();
            AtomicReference<String> action = new AtomicReference<>("");
            //first 基于su精确匹配
            var temp = className.split("/");
            String msu = "";
            if(temp.length>3){//默认命名空间的第四位是su
                msu = temp[3];
            }

            //也存在用第三位作为su的不规范项，第三位不为常见gs,igix,edp，则表明是不规范的行为
            if(temp.length>2 && temp[2].equalsIgnoreCase("gs") == false
                    &&temp[2].equalsIgnoreCase("igix") == false
                    &&temp[2].equalsIgnoreCase("edp") == false){
                msu = temp[2];
            }

            //caf的su，单独处理，因为有sys的也叫caf
            if(msu.length()>0 && msu.equalsIgnoreCase("caf")==false){
                var msuinfo = ConstantInfos.getMsuInfos();
                String finalMsu = msu;
                for (Map.Entry<String, List<String>> entry : msuinfo.entrySet()) {
                    String k = entry.getKey();
                    List<String> v = entry.getValue();
                    if (v.contains(finalMsu.toLowerCase())) {
                        action.set("请联系【" + k + "】处理");
                        break;
                    }
                }
            }

            //second 基于命名空间匹配
            var namespace = ConstantInfos.getNameSpace();
            final boolean[] isBreak = {false};
            for (Map.Entry<String, List<String>> entry : namespace.entrySet()) {
                String k = entry.getKey();
                List<String> v = entry.getValue();
                for (String y : v) {
                    if (className.contains(y)) {
                        action.set("请联系【" + k + "】处理");
                        isBreak[0] = true;
                        break;
                    }
                }
                if (isBreak[0]) {
                    break;
                }
            }

            if(action.get().length()>0){

            }else if(className.startsWith("io.iec.edp") ||
                    className.startsWith("com.inspur.edp") ||
                    className.startsWith("com.inspur.igix")){
                action.set("请联系【产品支持部】或者【平台部】处理");
            }else if(className.startsWith("com.inspur.gs")){
//            String[] names = className.split(".");
//            if(names.length>=4){
//                String code = names[3].toUpperCase();
//                if(KeyApps.containsKey(code)) {
//                    action.set(String.format("请联系【%s】处理！", KeyApps.get(code)));
//                }else{
//                    action.set("请联系【产品部】处理！");
//                }
//            }else{
                action.set("请联系【产品部】处理！");
//            }
            }else if(className.startsWith("inspur")){
                action.set("请联系【项目二开】处理！");
            }
//        else if(className.startsWith("inspur.cb")){
//            action.set("请联系【预算管理】处理！");
//        }
            action.set(action.get()+" : No Such Class '"+className);
            return new FailureAnalysis("No Such Class：" + cause.getMessage(),
                    action.get(),
                    rootFailure);
        }
//        return null;
    }
}
